package com.cy;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {

        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("text/html;charset=utf-8");

        HashMap<String, Object> map = new HashMap<>();
        map.put("status", 429);
        map.put("message", "访问太频繁，请稍后访问！");

        String jsonStr = new ObjectMapper().writeValueAsString(map);

        PrintWriter writer = httpServletResponse.getWriter();
        writer.println(jsonStr);

        writer.flush();

    }

}
